﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommandLine;
using System.Xml.Linq;
using System.Xml;

namespace dbschemaupdater
{
    class Program
    {
        class CmdArguments
        {
#pragma warning disable 0649

            [Argument(ArgumentType.Required, ShortName = "c", LongName = "connection", HelpText = "MSSQL database connection string")]
            public string connection;
            [Argument(ArgumentType.AtMostOnce, ShortName = "o", LongName = "output", HelpText = "Output file name", DefaultValue = "script.sql")]
            public string output;
            [Argument(ArgumentType.AtMostOnce, ShortName = "m", LongName = "model", HelpText = "Model file", DefaultValue = "model.xml")]
            public string model;
            [Argument(ArgumentType.AtMostOnce, ShortName = "g", LongName = "generate", HelpText = "Generate model file", DefaultValue = false)]
            public bool generate;

#pragma warning restore 0649
        }

        static void Main(string[] args)
        {
            CmdArguments cmdArgs = new CmdArguments();
            if (!CommandLine.Parser.ParseArgumentsWithUsage(args, cmdArgs))
            {
                System.Environment.ExitCode = 1;
                return;
            }

            try
            {
                if (cmdArgs.generate)
                {
                    var xdoc = Model.Generate(cmdArgs.connection);
                    xdoc.Save(cmdArgs.model);
                }
                else
                {
                    using (var reader = new System.IO.StreamReader(cmdArgs.model))
                    {
                        Model.Table[] model = Model.Load(reader);
                        using (var writer = new System.IO.StreamWriter(cmdArgs.output))
                        {
                            Generator.MakeScript(writer, model, cmdArgs.connection);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine();
                Console.Error.WriteLine("Error occured: {0}", ex.GetType().Name);
                Console.Error.WriteLine(ex.Message);
                if (!string.IsNullOrEmpty(ex.HelpLink))
                    Console.Error.WriteLine("See also: {0}", ex.HelpLink);

                Console.Error.WriteLine(ex.Source);
                Console.Error.WriteLine(ex.StackTrace);

                if (ex.InnerException != null)
                {
                    Console.Error.WriteLine(ex.InnerException.GetType().Name);
                    Console.Error.WriteLine(ex.InnerException.Message);
                }
                System.Environment.ExitCode = 1;
                return;
            }
        }
    }
}
